<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="分类名称" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-row :gutter="20">
      <el-col :span="12" :offset="0">
        <el-form-item label="父级类目" prop="parentId">
          <el-select v-model="ruleForm.parentId" placeholder="请选择父级类目">
            <el-option label="顶级类目" value="0-0"></el-option>
            <el-option
              v-for="item in cateList"
              :key="item.objectId"
              :label="item.name"
              :value="item.objectId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :offset="0">
        <el-form-item label="是否上架" prop="isonline">
          <el-switch v-model="ruleForm.isonline"></el-switch>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="分类图标" prop="icon">
      <el-input type="text" v-model="ruleForm.icon"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')"
        >立即创建</el-button
      >
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { categoryPost, categoryGet } from "@/api/job";
export default {
  data() {
    return {
      ruleForm: {
        name: "",
        parentId: "",
        isonline: false,
        icon: "",
      },
      rules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        parentId: [
          { required: true, message: "请选择父级类目", trigger: "blur" },
        ],
        isonline: [
          { required: true, message: "请选择上线状态", trigger: "blur" },
        ],
        icon: [{ required: true, message: "请上传图标", trigger: "blur" }],
      },
      cateList: [],
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          categoryPost(this.ruleForm);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  created() {
    // 方法1：在本地过滤顶级类目数据
    // categoryGet().then((res) => {
    //   console.log(res);
    //   let parentArr = res.data.results.filter((item) => item.parentId == "0-0");
    //   this.cateList = parentArr;
    // });
    // 方法2：修改api方法，支持条件查询
    categoryGet().then((res) => {
      console.log(res);
      this.cateList = res.data.results;
    });
  },
};
</script>
